﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FriendsNearby.Services.Entities;
using InSTEDD.Labs.Geo;

namespace FriendsNearby.Services
{
    class PersonNearbyBuilder
    {
        string hiddenUsersNamesFormat;
        int hiddenUsersCount;

        public PersonNearbyBuilder(string hiddenUsersNamesFormat)
        {
            this.hiddenUsersNamesFormat = hiddenUsersNamesFormat;
            hiddenUsersCount = 0;
        }

        public PersonNearby CreateFriendNearby(LocationInfo myInfo, LocationInfo friendInfo, string friendDisplayName, 
                                                        UserRegistry friendPreferences, PersonNearbyRelation relation)
        {
            if (friendPreferences.VisibilityLevel == (int)VisibilityLevel.Nobody)
                return null;

            PersonNearby person = new PersonNearby();
            person.UserID = friendInfo.UserID;
            person.FacebookUserID = friendPreferences.FacebookUserId;
            person.DisplayName = friendDisplayName;
            person.Relation = relation;
            person.Location = friendInfo.Location;
            person.LastLocationUpdate = friendInfo.When;
            person.Distance = myInfo.Location == null ? null : (double?)LatLong.DistanceInKm(myInfo.Location, friendInfo.Location);
            person.IsHidden = false;


            if (relation == PersonNearbyRelation.Friend)
            {
                person.CanRequestConnect = false;
                person.CanRequestContact = true;
            }
            else if (relation == PersonNearbyRelation.FriendOfAFriend)
            {
				if (friendPreferences.VisibilityLevel == (int)VisibilityLevel.ContactsAndTheirContacts
					|| friendPreferences.VisibilityLevel == (int)VisibilityLevel.Everyone)
                {
                    person.IsHidden = false;
                    person.DisplayName = friendDisplayName;
                }

				if (friendPreferences.VisibilityLevel == (int)VisibilityLevel.OnlyFriends)
                {
                    person.IsHidden = true;
                    hiddenUsersCount++;
                    person.DisplayName = string.Format(hiddenUsersNamesFormat, hiddenUsersCount);
                }

                person.CanRequestConnect = true;
                person.CanRequestContact = false;
            }

            return person;
        }

    }
}
